﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;

namespace VPLink2013.Webparts
{
    public class EspaceJediListItems : WebpartVPLink
    {
        public string strUrl { get; set; }
        public string strHtml { get; set; }
        private string strXslt { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Titre du bloc"), Category("Paramètres personnalisés")]
        public string blockTitle { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Page d'affichage de tous les éléments"), Category("Paramètres personnalisés")]
        public string blockPageName { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("XSl d'affichage"), Category("Paramètres personnalisés")]
        public string strXslFilePath { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Url de la liste"), Category("Paramètres personnalisés")]
        public string listUrl { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Page details"), Category("Paramètres personnalisés")]
        public string detailsPage { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Vue"), Category("Paramètres personnalisés"), DefaultValue("Tous les éléments")]
        public string Vue { get; set; }

        protected override string GetHtml()
        {
            strHtml = string.Empty;
            try
            {
                global = new GlobalVPLink2013();
                global.ListeAnnonces = new List<Annonce>();
                strUrl = SPContext.Current.Web.Url;
                ContextTrace.PrefixFileName = "webpart EspaceJedi";
                if (!string.IsNullOrEmpty(strXslFilePath))
                {
                    createAnounces();
                    string strXml = FileSerialization.CreateXmlStringFromObj(global);
                    strHtml = GetTransformFromStyleLibrary(strXml, strXslt);
                }
                else
                {
                    strHtml = "Vous devez reseigner le chemin du fichier xslt.";
                }
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace(string.Format("Exception : \n{0}", ex.ToString()));
            }
            return strHtml;
        }

        private void createAnounces()
        {
            try
            {
                using (SPSite site = new SPSite(strUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (!string.IsNullOrEmpty(listUrl))
                        {
                            SPList targetList = web.GetList(listUrl);
                            if (targetList != null)
                            {
                                global.TitreGlobal = blockTitle;
                                global.LienGlobal = string.Format("{0}/Pages/{1}", web.Url, blockPageName);
                                SPView chosenView = !string.IsNullOrEmpty(Vue) ? targetList.Views[Vue] : targetList.Views[0];
                                foreach (SPListItem item in targetList.GetItems(chosenView))
                                {
                                    Annonce announce = new Annonce();
                                    announce.ID = item.ID.ToString();
                                    announce.Titre = item.GetItemListFieldValueAsText("Titre");
                                    if (string.IsNullOrEmpty(announce.Titre))
                                    {
                                        announce.Titre = item.GetItemListFieldValueAsText("Title");
                                    }
                                    announce.TitrePiwik = announce.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
                                    announce.Chapeau = item.GetItemListFieldValueAsHtml("Description");
                                    announce.Photo1 = item.GetItemListFieldValueAsUrlValue("Photo");
                                    string dateFieldValue = item.GetItemListFieldValueAsDateTime("Date");
                                    if (!string.IsNullOrEmpty(dateFieldValue))
                                    {
                                        announce.DatePublication = dateFieldValue;
                                    }
                                    else
                                    {
                                        announce.DatePublication =item.GetItemListFieldValueAsDateTime("Created");
                                    }

                                    if (item.File != null)
                                    {
                                        announce.LinkDetail = string.Format("{0}/{1}", web.Url, item.File.Url);
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(detailsPage))
                                        {
                                            announce.LinkDetail = string.Format("{0}/Pages/{1}?itemId={2}", web.Url, detailsPage, announce.ID);
                                        }
                                        else
                                        {
                                            announce.LinkDetail = item.GetItemListFieldValueAsUrlValue("Lien");
                                        }
                                    }
                                    global.ListeAnnonces.Add(announce);
                                }
                                SPSecurity.RunWithElevatedPrivileges(delegate()
                                {
                                    strXslt = web.GetFileAsString(strXslFilePath);
                                });
                            }
                            else
                            {
                                strHtml = "Erreur lors de la recherche de la liste.";
                            }
                        }
                        else
                        {
                            strHtml = "Url de la liste non reconnue.";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace(string.Format("Exception lors de l'accès au site\n{0}", ex.Message));
                strHtml = "Exception lors de l'accès au site";
            }
        }
    }
}
